<template>
	<view class="order-confirm-page">
		<!-- 1. 顶部导航栏（固定，不滚动） -->
		<view class="nav-bar">
			<uni-icons type="left" size="24" class="nav-back" @click="handleGoBack"></uni-icons>
			<text class="nav-title">订单确认</text>
			<view class="nav-empty"></view>
		</view>

		<!-- 2. 中间内容容器（核心：可纵向滚动，包裹除导航和底部按钮外的所有内容） -->
		<view class="content-scroll">
			<!-- 2.1 收货地址区域 -->
			<view class="address-section">
				<view class="section-header">
					<text class="section-title">收货地址</text>
					<uni-icons type="right" size="18" class="section-icon" @click="handleChooseAddress"></uni-icons>
				</view>
				<view class="address-card" v-if="Object.keys(orderAddress).length > 0 || Object.keys(lastAddress).length > 0">
					<view v-if="Object.keys(orderAddress).length > 0">
						<view class="name-box" style="gap: 20rpx; margin-top: 10rpx">
							<text class="poi-name" style="font-weight: 600">{{ orderAddress.poiName }}</text>
							<text class="poi-detail">{{ orderAddress.detailAddress }}</text>
						</view>
						<view class="name-box" style="gap: 20rpx; margin-top: 10rpx">
							<text class="user-name">{{ orderAddress.recipient_name }}</text>
							<text class="user-phone">{{ orderAddress.recipient_phone }}</text>
						</view>
					</view>
					<view class="address-call" v-if="Object.keys(orderAddress).length === 0 && (Object.keys(lastAddress).length > 0 || addressList.length > 0)">
						<view class="address-call-title">最近使用过</view>
						<view class="name-box call" style="gap: 20rpx">
							<text class="poi-name">{{ addressList[0].poiName }}</text>
							<text class="poi-detail">{{ addressList[0].detailAddress }}</text>
						</view>
						<view class="name-box call" style="gap: 20rpx; margin-top: 10rpx">
							<text class="user-name" style="color: #fff">{{ addressList[0].recipient_name }}</text>
							<text class="user-phone" style="color: #fff">{{ addressList[0].recipient_phone }}</text>
						</view>
						<view class="usebtn" @click="usebtn(addressList[0])">使用</view>
					</view>
				</view>
				<view class="empty-address" v-if="Object.keys(orderAddress).length === 0" @click="handleChooseAddress">
					<view class="empty-address-placeholder">
						<uni-icons class="empty-icon" type="location" size="30" color="#bebebe"></uni-icons>
						<text class="empty-text">请选择地址</text>
					</view>
				</view>
			</view>

			<!-- 2.2 商品列表区域（修复：横向排列） -->
			<view class="goods-section">
				<view class="section-header">
					<text class="section-title">商品清单</text>
				</view>
				<!-- 商品横向滚动容器 -->
				<scroll-view scroll-x="true" class="goods-scroll" show-scrollbar="false" scroll-with-animation="true">
					<!-- 商品列表：强制横向排列 -->
					<view class="goods-list">
						<view class="goods-item" v-for="(item, index) in items" :key="item.id">
							<view class="goods-pic">
								<image :src="item.images[0].url || '/static/default-goods.png'" mode="aspectFill"></image>
							</view>
							<view class="goods-info">
								<text class="goods-name">{{ item.productName }}</text>
								<text class="goods-spec" v-if="item.spec">{{ item.specs }}</text>
								<view class="goods-price-count">
									<text class="goods-price">¥{{ (item.price || 0).toFixed(2) }}</text>
									<view class="goods-count">x{{ item.quantity || 1 }}</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 2.3 支付方式选择 -->
			<view class="pay-section">
				<view class="section-header">
					<text class="section-title">支付方式</text>
				</view>
				<view class="pay-methods">
					<view class="pay-method" :class="{ active: payId === 'wechat' }" @click="handleChangePay('wechat')">
						<image class="pay-icon wechat-icon" src="/static/weixi.png" mode=""></image>
						<text class="pay-name">微信支付</text>
						<uni-icons type="checkbox-filled" size="20" color="#ff4d4f" class="pay-check" v-if="payId === 'wechat'"></uni-icons>
					</view>
					<view class="pay-method" :class="{ active: payId === 'alipay' }" @click="handleChangePay('alipay')">
						<image class="pay-icon alipay-icon" src="/static/alipay.png" mode=""></image>
						<text class="pay-name">支付宝支付</text>
						<uni-icons type="checkbox-filled" size="20" color="#ff4d4f" class="pay-check" v-if="payId === 'alipay'"></uni-icons>
					</view>
					<view class="pay-method" :class="{ active: payId === 'cashier' }" @click="handleChangePay('cashier')">
						<image class="pay-icon cashier-icon" src="/static/cash.png" mode=""></image>
						<text class="pay-name">管家现结</text>
						<uni-icons type="checkbox-filled" size="20" color="#ff4d4f" class="pay-check" v-if="payId === 'cashier'"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 2.4 订单金额汇总 -->
			<view class="amount-section">
				<view class="amount-item">
					<text class="amount-label">商品总价</text>
					<text class="amount-value">¥{{ calculateTotalGoodsPrice().toFixed(2) }}</text>
				</view>
				<view class="amount-item">
					<text class="amount-label">运费</text>
					<text class="amount-value">¥{{ calculateFreight().toFixed(2) }}</text>
				</view>
				<view class="amount-item total-amount">
					<text class="amount-label">实付款</text>
					<text class="amount-value">¥{{ calculateFinalAmount().toFixed(2) }}</text>
				</view>
			</view>
		</view>

		<!-- 3. 提交订单按钮（固定底部，不滚动） -->
		<view class="submit-section">
			<button class="submit-btn" :disabled="!Object.keys(orderAddress).length > 0 || items.length === 0" @click="submit">提交订单</button>
		</view>
		<!-- <uni-pay @success="paySuccess" ref="pay"></uni-pay> -->
	</view>
</template>

<script>
const order = uniCloud.importObject('order',{customUI:true});
export default {
	name: 'orderSure',
	data() {
		return {
			isSure: false,
			payId: 'cashier',
			addressList: [],
			lastAddress: {},
			orderAddress: {},
			total_fee: 1, // 支付金额，单位分 100 = 1元
			order_no: '', // 业务系统订单号（即你自己业务系统的订单表的订单号）
			out_trade_no: '', // 插件支付单号
			description: '测试订单', // 支付描述
			type: 'test', // 支付回调类型 如 recharge 代表余额充值 goods 代表商品订单（可自定义，任意英文单词都可以，只要你在 uni-pay-co/notify/目录下创建对应的 xxx.js文件进行编写对应的回调逻辑即可）
			custom: {
				a: 'a',
				b: 1
			}
		};
	},
	computed: {
		items() {
			return this.$store.state.cart.items || [];
		},
		storeData() {
			return this.$store.state.msg || {};
		},
		systemInfo() {
			return this.$store.state.msg.systemInfo;
		}
	},
	mounted() {
		this.addressList = uni.getStorageSync('addressList') || [];
		this.lastAddress = uni.getStorageSync('lastAddress') || {};
		console.log(this.addressList);
		console.log(this.lastAddress);
		console.log(this.orderAddress);
		console.log('555', Object.keys(this.orderAddress).length === 0 && (Object.keys(this.lastAddress).length > 0 || this.addressList.length > 0));
	},
	methods: {
		handleGoBack() {
			uni.redirectTo({
				url: '/pages/shopcart/shopcart'
			});
		},
		handleChooseAddress() {
			uni.navigateTo({
				url: '/pages/myAddress/myAddress',
				events: {
					fromB: (res) => {
						this.orderAddress = res;
						console.log('地址', this.addressList.length);
						console.log('传回的地址', res);
					}
				}
			});
		},
		usebtn(item) {
			this.orderAddress = item;
			this.$store.commit('cart/SET_lastAddress', item);
		},
		handleChangePay(payType) {
			this.payId = payType;
		},
		calculateTotalGoodsPrice() {
			return this.items.reduce((total, item) => {
				const price = Number(item.price) || 0;
				const quantity = Number(item.quantity) || 1;
				return total + price * quantity;
			}, 0);
		},
		calculateFreight() {
			const totalGoodsPrice = this.calculateTotalGoodsPrice();
			return totalGoodsPrice >= 99 ? 0 : 10;
		},
		calculateFinalAmount() {
			return this.calculateTotalGoodsPrice() + this.calculateFreight();
		},
		async submit() {
			if (this.items.length === 0) {
				return uni.showToast({ title: '无订单商品', icon: 'none' });
			}
			if (!this.storeData?.user?.userId) {
				return uni.showToast({ title: '请先登录', icon: 'none' });
			}
			if (!this.orderAddress._id) {
				return uni.showToast({ title: '请选择收货地址', icon: 'none' });
			}

			//uni.showLoading({ title: '订单提交中...', mask: true });
			try {
				// const payNameMap = {
				// 	wechat: '微信支付',
				// 	alipay: '支付宝支付',
				// 	cashier: '管家现结'
				// };
				const orderData = {
					userId: this.storeData.user.userId,
					productList: this.items,
					addressId: this.orderAddress.id,
					payId: this.payId,
					totalAmount: this.calculateTotalGoodsPrice(),
					freight: this.calculateFreight(),
					finalAmount: this.calculateFinalAmount()
				};
               
				const data = await order.createOrder(orderData);
				uni.hideLoading();
				if (data.success) {
					
					//测试逻辑
					this.paySuccess()
					
					// this.pay(data.orderId,this.calculateFinalAmount().toFixed(2))//待支付正式上线
					
			
				} else {
					uni.showModal({
						title: '下单失败',
						content: data.message || '系统异常，请稍后重试',
						showCancel: false
					});
				}
			} catch (error) {
				//uni.hideLoading();
				uni.showToast({ title: '网络异常，请重试', icon: 'none' });
				console.error('下单出错：', error);
			}
		},
		pay(orderId,total_fee){
			this.order_no = `test` + Date.now(); // 模拟生成订单号
			this.out_trade_no = `${this.order_no}-1`; // 模拟生成插件支付单号
			// 打开支付收银台
			this.$refs.pay.open({
				total_fee: total_fee, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
				order_no: orderId, // 业务系统订单号（即你自己业务系统的订单表的订单号）
				out_trade_no: this.out_trade_no, // 插件支付单号
				description: this.description, // 支付描述
				type: 'goods', // 支付回调类型
				custom: this.custom // 自定义数据（此参数不推荐使用，因为是前端传的，此参数可能会被伪造，建议通过order_no查询自己业务订单表来获取自定义业务数据）
			});
		},
		paySuccess(res){
		     console.log('支付成功回调',res);	
			 uni.showModal({
			 	title: '下单成功',
			 	showCancel: false,
			 	success: (res) => {
			 		if (res.confirm) {
			 			this.$store.commit('cart/clearCart');
			 			this.lastAddress = this.orderAddress;
			 			uni.setStorageSync('lastAddress', this.orderAddress);
			 			this.$emit('closePopup');
			 			uni.navigateTo({ url: '/pages/orderList/orderList' });
			 		}
			 	}
			 });
		},
		payFail(res){
			console.log('支付失败回调',res)
		}
	}
};
</script>

<style lang="scss" scoped>
/* 全局容器：确保页面高度100% */
.order-confirm-page {
	position: relative;
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* 1. 顶部导航栏（固定） */
.nav-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 99;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 100rpx;
	padding: 0 30rpx;
	background-color: #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.nav-back {
	color: #333;
}
.nav-title {
	font-size: 36rpx;
	font-weight: 500;
	color: #333;
}
.nav-empty {
	width: 24px;
}

/* 2. 中间内容容器（可纵向滚动） */
.content-scroll {
	padding: 120rpx 20rpx 130rpx; /* 上：避开导航，下：避开底部按钮，左右：留白 */
	overflow-y: auto; /* 开启纵向滚动 */
	max-height: 100vh; /* 限制高度为屏幕高度，确保滚动生效 */
	box-sizing: border-box;
}

/* 2.1 地址区域样式 */
.address-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
}
.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}
.section-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}
.section-icon {
	color: #999;
}
.address-card {
	position: relative;
	padding: 20rpx;
	border-radius: 12rpx;
	background-color: #fafafa;
}
.empty-address {
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 10rpx;
	background-color: #f4f4f4;
	padding: 15rpx 0;
}
.empty-address {
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 10rpx;
	background-color: #f4f4f4;
	padding: 15rpx 0;
	/* 关键：添加过渡动画，让变化更平滑 */
	transition: all 0.15s ease;
	/* 去除默认点击高亮（可选，提升体验） */
	-webkit-tap-highlight-color: transparent;
}

.empty-address:active {
	transform: scale(0.98);

	background-color: #e8e8e8;
}

/* 内部文字也可轻微变色（可选） */
.empty-address:active .empty-text {
	color: #666; /* 比原#999稍深 */
}
.empty-address-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
}
.empty-icon {
	color: #957ccc;
	margin-bottom: 16rpx;
}
.empty-text {
	font-size: 28rpx;
	color: #b4b4b4;
}
.user-name {
	font-size: 32rpx;
	color: #000;
	font-weight: 400;
}
.user-phone {
	font-size: 28rpx;
	color: #666;
}
.name-box {
	display: flex;
}

/* 2.2 商品列表样式（关键：横向排列） */
.goods-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
}
/* 商品横向滚动容器：固定宽度 */
.goods-scroll {
	width: 100%;
	overflow-x: auto;
	margin-top: 16rpx;
	border-radius: 12rpx;
	background-color: #fafafa;
	padding: 15rpx 0;
}
/* 商品列表：强制横向排列 */
.goods-list {
	display: flex; /* 核心：flex布局横向排列 */
	gap: 20rpx; /* 商品间距 */
	padding: 0 15rpx; /* 左右留白 */
}
/* 商品项：固定宽度，避免换行 */
.goods-item {
	flex: 0 0 auto; /* 关键：不收缩、不拉伸，保持固定宽度 */
	width: 150rpx; /* 固定宽度，确保横向溢出 */
	display: flex;
	flex-direction: column;
	background-color: #fff;
	padding: 12rpx;
	border-radius: 12rpx;
}
/* 商品图片 */
.goods-pic {
	width: 140rpx;
	height: 140rpx;
	border-radius: 8rpx;
	overflow: hidden;
	margin-bottom: 16rpx;
}
.goods-pic image {
	width: 100%;
	height: 100%;
}
/* 商品信息 */
.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}
.goods-name {
	font-size: 26rpx;
	color: #333;
	line-height: 36rpx;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	margin-bottom: 8rpx;
}
.goods-spec {
	font-size: 22rpx;
	color: #999;
	margin-bottom: 16rpx;
	flex: 1;
}
.goods-price-count {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.goods-price {
	font-size: 30rpx;
	color: #ff4d4f;
	font-weight: 500;
}
.goods-count {
	font-size: 24rpx;
	color: #999;
}
.empty-goods {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 200rpx;
	width: 100%;
	color: #999;
	font-size: 28rpx;
}

/* 2.3 支付方式样式 */
.pay-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
}
.pay-methods {
	display: flex;
	justify-content: space-around;
	gap: 24rpx;
	margin-top: 16rpx;
}
.pay-method {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 18rpx;
	gap: 15rpx;
	border-radius: 12rpx;
	background-color: #fafafa;
	position: relative;
	transition: all 0.2s;
}
.pay-method.active {
	background-color: #fff;
	border: 2rpx solid #ff4d4f;
}
.pay-icon {
	width: 80rpx;
	height: 80rpx;
}
.wechat-icon {
	color: #07c160;
}
.alipay-icon {
	color: #1677ff;
}
.cashier-icon {
	color: #ff9f1c;
}
.pay-name {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}
.pay-check {
	color: #ff4d4f;
	position: absolute;
	right: 18rpx;
}

/* 2.4 金额汇总样式 */
.amount-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 16rpx;
}
.amount-item {
	display: flex;
	justify-content: space-between;
	padding: 16rpx 0;
	font-size: 28rpx;
}
.amount-label {
	color: #666;
}
.amount-value {
	color: #333;
}
.total-amount {
	border-top: 1rpx solid #f0f0f0;
	margin-top: 8rpx;
	padding-top: 24rpx;
}
.total-amount .amount-label {
	font-weight: 500;
	color: #333;
}
.total-amount .amount-value {
	font-size: 32rpx;
	color: #ff4d4f;
	font-weight: 500;
}

/* 3. 提交订单按钮（固定底部） */
.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 99;
	padding: 20rpx;
	background-color: #fff;
	box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.05);
}
.submit-btn {
	width: 100%;
	height: 90rpx;
	background-color: #ff4d4f;
	color: #fff;
	font-size: 32rpx;
	border-radius: 45rpx;
}
.submit-btn:disabled {
	background-color: #ffcccc;
	color: #fff;
}

/* 地址气泡样式 */
.address-call {
	position: absolute;
	top: 110%;
	left: 20rpx;
	z-index: 10;
	display: flex;
	padding: 20rpx 10rpx;
	flex-direction: column;
	width: 400rpx;
	height: 120rpx;
	background-color: #333;
	border-radius: 10rpx;
	color: #fff;
	.address-call-title {
		margin-bottom: 15rpx;
		font-size: 24rpx;
	}
}
::v-deep .address-call::after {
	content: '';
	position: absolute;
	top: -20rpx;
	left: 20%;
	transform: translateX(-50%);
	width: 0;
	height: 0;
	border-left: 20rpx solid transparent;
	border-right: 20rpx solid transparent;
	border-bottom: 20rpx solid #333;
}
.call {
	color: #fff;
}
.usebtn {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	font-size: 26rpx;
	padding: 8rpx 16rpx;
	background-color: #999;
	color: #fff;
	border-radius: 6rpx;
}
</style>
